<?php
namespace app\common\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;

/**
 * 删除无效图片
 * @author King
 *
 */
class DeleteInvalidPic extends Command
{

	protected $logName = 'deleteInvalidPic';
	protected $mes = '';
	protected $isPrint = 1;	// 是否打印信息到终端

	protected function configure()
	{
		$this->setName('deleteInvalidPic')
		->setDescription('删除无效图片');
	}

	protected function execute(Input $input, Output $output)
	{
		set_time_limit(0);
		ini_set('memory_limit', '512M');
		error_reporting(E_ALL & ~E_NOTICE);

		$skuPicList = db('sku')->column('pic');
		foreach ($skuPicList as &$v) {
			$v = basename($v);
		}
		$picList2 = db('wechat_user')->column('avatar');
		foreach ($picList2 as &$a) {
			$a = basename($a);
		}
		$skuPicList = array_merge($skuPicList, $picList2);
		$picList3 = db('material')->column('pic');
		foreach ($picList3 as &$b) {
			$b = basename($b);
		}
		$skuPicList = array_merge($skuPicList, $picList3);
		$picList4 = db('stall_cost')->column('pic');
		foreach ($picList4 as &$c) {
			$c = basename($c);
		}
		$skuPicList = array_merge($skuPicList, $picList4);
		$skuPicList = array_unique($skuPicList);

		$uploadDir = env('root_path').'public/upload/';
		for ($year=2022; $year<=2022; $year++) {
			for ($m=1; $m<=12; $m++) {
				$month = str_pad($m, 2, 0, STR_PAD_LEFT);
				if (file_exists($uploadDir . $year.$month)) {
					for ($d=1; $d<=31; $d++) {
						$day = str_pad($d, 2, 0, STR_PAD_LEFT);
						if (file_exists($uploadDir . $year.$month . '/' . $day)) {
							$dir = $uploadDir. $year.$month . '/' . $day . '/';
							echo "start scandir[{$dir}]".PHP_EOL;
							$list = scandir($dir);
							foreach ($list as $f) {

								if ($f!='.' && $f!='..' && $f!='.svn') {
									echo $year.$month . '/' . $day . '/'.$f.'..........';

									if (!in_array($f, $skuPicList)) {
										if(unlink($dir.$f)) echo 'delete ok'.PHP_EOL;
										else echo 'delete error'.PHP_EOL;
									} else echo 'used'.PHP_EOL;

								} else echo "not file".PHP_EOL;
							}
						}
					}
				}
			}
		}
		echo "Done".PHP_EOL;
	}

}